<template>
  <div class="page">
    <Navbar :show-navbar="false"/>
    <div class="content">
      <div class="home-header">
        <image src="/static/home/title.png" alt="" style="width: 200rpx;height: 48rpx"/>
        <view class="location" @click="changeCity">
          <text>{{ (currentCity.name || '').replace('市', '') }}</text>
          <u-icon style="margin: 0 12rpx" size="24rpx" name="arrow-down-fill"></u-icon>
        </view>
      </div>
      <div class="filter-box">
        <u-dropdown active-color="#04C8AE">
          <u-dropdown-item
              @change="getList(true)"
              v-model="searchForm.sortType" :title="formatSearchForm.sortTypeLabel || '综合排序'" :options="options1"></u-dropdown-item>
          <u-dropdown-item
              @change="getList(true)"
              v-model="searchForm.distance" :title="formatSearchForm.distanceLabel || '距离'" :options="options2"></u-dropdown-item>
          <u-dropdown-item
              @change="getList(true)"
              v-model="searchForm.speedType" :title="formatSearchForm.speedTypeLabel || '充电速度'" :options="options3"></u-dropdown-item>
        </u-dropdown>
      </div>
      <view class="home-content">
        <scroll-view
            scroll-y="true"
            @scrolltolower="onScroll"
            refresher-enabled
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh"
            style="height: 100%"
        >
          <StationItem v-for="item in dataList" :key="item.id" :station="item" />
          <u-loadmore v-if="dataList.length" :status="loading" />
          <div style="height: 40px"></div>

          <u-empty  v-if="dataList.length === 0" mode="list"></u-empty>
        </scroll-view>

        <Tabbar/>
      </view>
    </div>
  </div>
</template>
<script>
import Tabbar from "../../components/Tabbar.vue";
import StationItem from "../station/item.vue";
import Navbar from "../../components/navbar.vue";

export default {
  name: "index" ,
  components: {Navbar, StationItem, Tabbar},
  data() {
    return {
      isRefreshing: false,
      currentCity: {
        name: '定位中...',
        code: ''
      },
      // 经纬度信息
      location: {
        latitude: 23.129163,
        longitude: 113.264435
      },
      searchForm: {
        sortType: 1,
        distance: '',
        speedType: -1,
      },
      options1: [
          {
            label: '综合排序',
            value: 1,
          },
          {
            label: '离我最近',
            value: 2,
          },
          {
            label: '价格最低',
            value: 3,
          },
          {
            label: '空闲最多',
            value: 4,
          },
      ],
      options2: [
          // 1km 2km 3km 4km 5km
          {
            label: '全部',
            value: '',
          },
        {
          label: '1km',
          value: 1,
        },
          {
            label: '2km',
            value: 2,
          },
          {
            label: '3km',
            value: 3,
          },
          {
            label: '4km',
            value: 4,
          },
          {
            label: '5km',
            value: 5,
          },
          // 10km 20km 30km 40km 50km
          {
            label: '10km',
            value: 10,
          },
          {
            label: '20km',
            value: 20,
          },
          {
            label: '30km',
            value: 30,
          },
          {
            label: '40km',
            value: 40,
          },
          {
            label: '50km',
            value: 50,
          },
      ],
      options3: [
        {
          label: '全部',
          value: -1,
        },
        {
          label: '快充',
          value: 1,
        },
        {
          label: '慢充',
          value: 0,
        },
      ],
      dataList: [
      ],
      loading: 'loading',
      pageNo: 1,
      total: 0
    }
  },
  onLoad() {
    // 监听城市选择事件
    uni.$on('citySelected', this.handleCitySelected)
  },
  onUnload() {
    // 移除事件监听
    uni.$off('citySelected', this.handleCitySelected)
  },
  onShow() {
    // 获取存储的城市
    const savedCity = uni.getStorageSync('selectedCity')
    if (savedCity) {
      if (this.currentCity.name === savedCity.name ) {
        return
      }
      this.currentCity = {
        ...savedCity
      }
      uni.getLocation({
        type: 'gcj02',
        success: res => {
          this.location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
        },
        complete: () => {
          this.getList(true)
        }
      })
    } else {
      // 去城市定位页面
      uni.navigateTo({
        url: '/pages/city/index'
      })
    }
  },
  computed: {
    formatSearchForm() {
      let distance = ''
      let sortType = ''
      let speedType = ''
      let distanceLabel = ''
      let sortTypeLabel = ''
      let speedTypeLabel = ''
      let findDistance = this.options2.find(item => item.value === this.searchForm.distance)
      if (findDistance) {
        distance = findDistance.value
        distanceLabel = findDistance.label
      }
      let findSortType = this.options1.find(item => item.value === this.searchForm.sortType)
      if (findSortType) {
        sortType = findSortType.value
        sortTypeLabel = findSortType.label
      }
      let findSpeedType = this.options3.find(item => item.value === this.searchForm.speedType)
      if (findSpeedType) {
        speedType = findSpeedType.value
        speedTypeLabel = findSpeedType.label
      }
      return {
        distance: distance == -1 ? -1 : distance,
        distanceLabel: distanceLabel === '全部' ? '' : distanceLabel,
        sortType,
        sortTypeLabel,
        speedType: speedType == -1 ? -1 : speedType,
        speedTypeLabel: speedTypeLabel === '全部' ? '' : speedTypeLabel
      }
    }
  },
  methods: {
    // 处理城市选择
    handleCitySelected(city) {
      this.currentCity = city
      // 这里可以根据选择的城市重新加载地图数据
      console.log('选择的城市:', city)
      this.getList(true)
    },
    changeCity() {
      uni.navigateTo({
        url: '/pages/city/index'
      })
    },
    async getList(reset = false) {
      if (reset) {
        this.pageNo = 1
        this.dataList = []
      } else {
        if (this.loading === 'nomore') return
      }
      this.loading = 'loading'
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const res = await this.$api.getChargeStationList({
          pageNo: this.pageNo,
          pageSize: 10,
          city: this.currentCity.code ? this.currentCity.name : '',
          ...this.location,
          // 格式化请求参数
          ...this.searchForm,
          distance: this.searchForm.distance == -1 ? '' : this.searchForm.distance,
          speedType: this.searchForm.speedType == -1 ? '' : this.searchForm.speedType
        })
        const { list, total } = res
        this.total = total || 0
        if (reset) {
          this.dataList = list || []
        } else {
          this.dataList = [...this.dataList, ...(list || [])]
        }

        this.pageNo++
        this.loading = (list || []).length >= this.total ? 'nomore' : 'loadmore'
        uni.hideLoading()
      } catch (e) {
        console.log(e)
        this.loading = 'loadmore'
      }
    },
    // 下拉刷新
    async onRefresh() {
      if (this.isRefreshing) return
      this.isRefreshing = true

      try {
        await this.getList(true)
        uni.showToast({
          title: '刷新成功',
          icon: 'none'
        })
      } catch (e) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      } finally {
        this.isRefreshing = false
      }
    },

    // 上拉加载更多
    onScroll() {
      if (this.loading === 'loading') return
      this.getList()
    },
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getList()
  }
}
</script>

<style scoped lang="scss">
.home-header {
  background-color: #ffffff;
  padding: 16rpx 32rpx 24rpx;
  display: flex;
  align-items: center;

  .location {
    display: flex;
    align-items: center;
    margin-left: 12rpx;
  }
}
.home-content {
  flex: 1;
  height: 0;
  position: relative;
  background-color: #F3F5F5;
  padding-top: 24rpx;

  :deep(.scroll-view) {
    height: 100%;
  }

  :deep(.uni-scroll-view-refresh) {
    background: #f5f5f5;
  }
}

</style>
